import pdfplumber
from PIL import Image
import os
import logging
class PdfToImageConverter:
    def __init__(self, output_dir):
        self.output_dir = output_dir
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

    def convert_pdf_to_images(self, fnm, zoomin=3, page_from=0, page_to=299):
        try:
            self.pdf = pdfplumber.open(fnm) if isinstance(fnm, str) else pdfplumber.open(BytesIO(fnm))
            for i, page in enumerate(self.pdf.pages[page_from:page_to]):
                img = page.to_image(resolution=72 * zoomin).original
                img_path = os.path.join(self.output_dir, f"page_{i + page_from + 1}.png")
                img.save(img_path)
                logging.debug(f"Saved image: {img_path}")
        except Exception as e:
            logging.exception(f"Failed to convert PDF to images: {str(e)}")


# 使用示例
if __name__ == "__main__":
    input_pdf_path = './pdfs/GB_T 10123-2022_7169_PDF_CN_DoubleLayer.pdf'
    output_folder = 'images'
    converter = PdfToImageConverter(output_dir=output_folder)
    converter.convert_pdf_to_images(fnm=input_pdf_path)